using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Dimok.Data.DataSources;

namespace Data.DataSources {
	public class CollectionsDataSource : ObjectDataSourceBase {
		const string DATE_DUE_FROM = "DateDueFrom";
		const string DATE_DUE_TO = "DateDueTo";
		string _svn = "v_Collection";
		public override string SelectViewName { get { return _svn; } set { _svn = value; } }
		public override string InsertViewName { get { return "t_Collection"; } }
		public string DateDueFrom {
			set {
				SelectMethod = "SelectByDateDue";
				MakeFilter(value, GetSelectParameterString(DATE_DUE_TO) + "");
			}
		}
		public string DateDueTo {
			set {
				SelectMethod = "SelectByDateDue";
				MakeFilter(GetSelectParameterString(DATE_DUE_FROM) + "", value);
			}
		}
		void MakeFilter(string dateFrom, string dateTo) {
			DateTime DateMin = new DateTime(1753, 1, 1);
			DateTime DateMax = new DateTime(9999, 1, 1);
			if (dateFrom == "" && dateTo == "") {
				SelectMethod = SELECT_METHOD;
				RemSelectParameter(DATE_DUE_FROM);
				RemSelectParameter(DATE_DUE_TO);
				return;
			}
			DateTime dtf = DateMin;
			if (dateFrom != "" && !DateTime.TryParse(dateFrom, out dtf))
				throw new Exception("Date From is incorrect.");
			DateTime dtt = DateMax;
			if (dateTo != "" && !DateTime.TryParse(dateTo, out dtt))
				throw new Exception("Date To is incorrect.");
			SetSelectParameter(DATE_DUE_FROM, dtf.ToString("d"));
			SetSelectParameter(DATE_DUE_TO, dtt.ToString("d"));
			if( GetSelectParameterDate(DATE_DUE_FROM) == DateMin &&
					GetSelectParameterDate(DATE_DUE_TO) == DateMax ){
				SelectMethod = SELECT_METHOD;
				RemSelectParameter(DATE_DUE_FROM);
				RemSelectParameter(DATE_DUE_TO);
				return;
			}
		}
		public override DataView SelectEx() {
			return base.SelectEx();
		}
		public DataView SelectByDateDue(DateTime DateDueFrom,DateTime DateDueTo ) {
			UseNoLock = false;
			SelectViewName = "CollectionsByDateDue(@DDF,@DDT)";
			return Select("",DateDueFrom,DateDueTo);
		}
	}
}